"""
七牛云图片上传服务
支持从URL下载图片并上传到七牛云，使用七牛云图片处理API生成缩略图
"""
import os
import uuid
import httpx
import logging
from typing import List, Tuple, Optional, Dict
from qiniu import Auth, put_data
from config.qiniu_config import QINIU_CONFIG
from utils.log_context import RequestContext, ContextLogger

# 使用新的统一日志配置
from config.logging_config import ProjectLoggers
logger = ProjectLoggers.get_qiniu_logger()

# 创建带请求ID的日志记录器
context_logger = ContextLogger(logger)

class QiniuImageService:
    """七牛云图片上传服务"""
    
    def __init__(self):
        self.auth = Auth(QINIU_CONFIG['access_key'], QINIU_CONFIG['secret_key'])
        self.bucket_name = QINIU_CONFIG['bucket_name']
        self.domain = QINIU_CONFIG['domain']
        logger.info("☁️ 七牛云图片服务初始化完成")
    
    async def upload_images_from_urls(self, image_urls: List[str], request_id: Optional[str] = None) -> List[str]:
        """
        从URL列表下载图片并上传到七牛云
        
        参数:
        - image_urls: 图片URL列表
        - request_id: 请求ID，用于日志跟踪 (可选)
        
        返回:
        - 七牛云原图URL列表
        """
        # 如果传入了请求ID，设置到当前上下文
        if request_id:
            RequestContext.set_request_id(request_id)
        
        context_logger.info(f"☁️ 开始批量上传图片到七牛云，共 {len(image_urls)} 张")
        qiniu_urls = []
        
        for i, url in enumerate(image_urls):
            try:
                context_logger.info(f"📤 正在处理第 {i+1}/{len(image_urls)} 张图片: {url[:100]}...")
                
                # 下载图片
                image_data = await self._download_image(url)
                if image_data:
                    # 上传图片到七牛云
                    qiniu_url = await self._upload_image(image_data)
                    if qiniu_url:
                        qiniu_urls.append(qiniu_url)
                        context_logger.info(f"✅ 上传成功: {qiniu_url}")
                    else:
                        context_logger.error(f"❌ 上传失败: {url}")
                else:
                    context_logger.error(f"❌ 下载失败: {url}")
            except Exception as e:
                context_logger.error(f"❌ 处理图片异常: {url}, 错误: {str(e)}")
                continue
        
        context_logger.info(f"🎯 批量上传完成，成功: {len(qiniu_urls)}/{len(image_urls)}")
        return qiniu_urls
    
    async def _download_image(self, url: str) -> Optional[bytes]:
        """从URL下载图片数据"""
        try:
            # 使用较短的超时时间，避免阻塞webhook处理
            async with httpx.AsyncClient(timeout=15.0) as client:
                response = await client.get(url)
                if response.status_code == 200:
                    return response.content
                else:
                    context_logger.error(f"下载图片失败，状态码: {response.status_code}, URL: {url}")
                    return None
        except Exception as e:
            context_logger.error(f"下载图片异常: {url}, 错误: {str(e)}")
            return None
    
    async def _upload_image(self, image_data: bytes) -> Optional[str]:
        """上传图片到七牛云"""
        try:
            # 生成唯一文件名
            file_id = f"xmai-{str(uuid.uuid4()).replace('-', '')}"
            
            # 使用jpg格式以获得更好的兼容性
            key = f"images/{file_id}.jpg"
            
            # 上传到七牛云
            qiniu_url = await self._upload_to_qiniu(image_data, key)
            return qiniu_url
                
        except Exception as e:
            context_logger.error(f"上传图片异常: {str(e)}")
            return None
    
    def generate_thumbnail_url(self, original_url: str, width: int = 300, height: int = 300) -> str:
        """
        使用七牛云图片处理API生成缩略图URL
        
        参数:
        - original_url: 原图URL
        - width: 缩略图宽度，默认300
        - height: 缩略图高度，默认300
        
        返回:
        - 缩略图URL
        """
        # 七牛云imageView2参数说明：
        # /1/w/300/h/300 - 等比缩放，限定在300x300内
        # /2/w/300/h/300 - 等比缩放，限定在300x300内，居中裁剪
        # /q/85 - 图片质量85%
        thumbnail_params = f"?imageView2/1/w/{width}/h/{height}/q/85"
        return original_url + thumbnail_params
    
    def generate_thumbnail_urls(self, original_urls: List[str], width: int = 300, height: int = 300) -> List[str]:
        """
        批量生成缩略图URL
        
        参数:
        - original_urls: 原图URL列表
        - width: 缩略图宽度，默认300
        - height: 缩略图高度，默认300
        
        返回:
        - 缩略图URL列表
        """
        return [self.generate_thumbnail_url(url, width, height) for url in original_urls]
    
    async def _upload_to_qiniu(self, data: bytes, key: str) -> Optional[str]:
        """上传数据到七牛云"""
        try:
            # 获取上传token
            token = self.auth.upload_token(self.bucket_name)
            
            # 上传数据
            ret, info = put_data(token, key, data)
            
            if info.status_code == 200 and ret:
                # 返回访问URL
                return f"https://{self.domain}/{key}"
            else:
                context_logger.error(f"上传到七牛云失败: {info.text_body}")
                return None
                
        except Exception as e:
            context_logger.error(f"上传到七牛云异常: {str(e)}")
            return None

# 创建服务实例
qiniu_image_service = QiniuImageService() 